<template>
  <el-row>
    <el-row>
      <div id="iframe" style="position: fixed;left: 30%;z-index: 100;" />
      <button id="cs_msisdn" style="display: none">{{ $t('collectDetail.dialNumber') }}</button>
    </el-row>
    <el-container>
      <el-aside width="200px">
        <el-card style="width: 200px;">
          <el-row>
            <el-button
              type="primary"
              @click="goAnchor('orderDetail')"
            >
              {{ $t('collectDetail.loanOrderInfo') }}
            </el-button>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-button
              type="primary"
              @click="goAnchor('reviewInfo')"
            >
              {{ $t('collectDetail.auditOrder') }}
            </el-button>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-button
              type="primary"
              @click="goAnchor('contactPerson')"
            >
              {{ $t('collectDetail.friendInfo') }}
            </el-button>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-button
              type="primary"
              @click="goAnchor('addressBook')"
            >
              {{ $t('collectDetail.contactBook') }}
            </el-button>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-button
              type="primary"
              @click="goAnchor('letterReview')"
            >
              {{ $t('letterReviewOrder.letterRecord') }}
            </el-button>
          </el-row>
        </el-card>
      </el-aside>
      <el-main id="sectionInfo">
        <el-row style="height: 600px;min-width: 800px">
          <el-row id="orderDetail">
            <order-detail />
          </el-row>
          <el-row id="reviewInfo" style="padding: 0 10px">
            <review-info
              :order-info-data="orderInfoData"
              :user-contact-data="userContactData"
              :user-info-data="userInfoData"
              @set-contact-state="setContactState"
            />
          </el-row>

          <el-row v-if="phoneData.length > 0" id="addressBook" style="padding: 0 10px">
            <el-card>
              <el-collapse accordion value="1">
                <el-collapse-item name="1">
                  <template slot="title">
                    {{ $t('authModule.addressBook') }}
                  </template>
                  <address-book
                    :phone-data="phoneData"
                    @set-contact-state="setContactState"
                  />
                </el-collapse-item>
              </el-collapse>
            </el-card>
          </el-row>
          <el-row id="letterReview" style="padding: 10px">
            <el-card>
              <el-collapse accordion value="1">
                <el-collapse-item name="1">
                  <template slot="title">
                    {{ $t('letterReviewOrder.letterRecord') }}
                  </template>
                  <letter-review v-loading="letterRecordLoading" :credit-order-no="creditOrderNo" :letter-record-data="letterRecordData" />
                </el-collapse-item>
              </el-collapse>
            </el-card>
          </el-row>
        </el-row>
      </el-main>
      <el-aside width="200px">
        <el-card style="width: 200px;text-align: center">
          <h3>
            {{ userInfoData && userInfoData['phoneNumber'] ? userInfoData['phoneNumber'] : '' }}
          </h3>
          <el-row>
            <el-button
              type="primary"
              @click="phoneFn('isPhone')"
            >
              {{ $t('collectDetail.dial') }}
            </el-button>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-button
              type="primary"
              @click="phoneFn('isSms')"
            >
              {{ $t('collectDetail.sendMessage') }}
            </el-button>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-button
              type="primary"
              @click="copyClipboard()"
            >
              {{ $t('collectDetail.copyPhone') }}
            </el-button>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-button
              :loading="copyLoading"
              type="primary"
              @click="copyCode()"
            >
              {{ $t('collectDetail.copyLink') }}
            </el-button>
          </el-row>
        </el-card>
      </el-aside>
    </el-container>
    <el-divider />
    <el-tabs type="border-card">
      <el-tab-pane :label="$t('collectDetail.collectionLog')">
        <collection-log />
      </el-tab-pane>
      <el-tab-pane :label="$t('collectDetail.collectionPhone')">
        <call-components />
      </el-tab-pane>
      <el-tab-pane :label="$t('collectDetail.collectionSms')">
        <sms-components />
      </el-tab-pane>
      <el-tab-pane :label="$t('collectDetail.collectionFlow')">
        <collection-flow />
      </el-tab-pane>
      <el-tab-pane :label="$t('collectDetail.repaymentCode')">
        <repayment-code ref="repaymentCode" @set-copy-loading="setCopyLoading" />
      </el-tab-pane>
    </el-tabs>
    <phone-dialog :show-dialog="isPhone" :user-contact-data="userContactData" :phone-data="phoneData" @change-dialog="changeDialog" @set-contact-state="setContactState" @call-phone="callPhone" />
    <sms-dialog :show-dialog="isSms" :staff-data="staffData" :user-contact-data="userContactData" :phone-data="phoneData" @change-dialog="changeDialog" @set-contact-state="setContactState" />
  </el-row>
</template>

<script>
import { orderInfo, userContact, updateUserContactStatusput, userInfo } from '@/api/auth'
import { getCurrentStaffId } from '@/api/risk'
import { riskAuditDetail } from '@/api/risk'
import orderDetail from '@/views/order/orderDetail'
import collectionLog from '@/views/collection/collectionLog'
import repaymentCode from '@/views/order/repaymentCode'
import callComponents from '@/views/collection/record/call'
import smsComponents from '@/views/collection/record/sms'
import reviewInfo from '@/components/auth/reviewInfo'
import collectionFlow from '@/components/collection/collection-flow'
import addressBook from '@/components/auth/addressBook'
import letterReview from '@/components/auth/letter-review'
import phoneDialog from '@/components/risk/auth/phone-dialog'
import smsDialog from '@/components/risk/auth/sms-dialog'
export default {
  name: 'CollectDetail',
  components: {
    orderDetail,
    reviewInfo,
    addressBook,
    letterReview,
    phoneDialog,
    smsDialog,
    collectionLog,
    callComponents,
    smsComponents,
    collectionFlow,
    repaymentCode
  },
  data() {
    return {
      para: this.$route.query,
      orderInfoData: {},
      userInfoData: {},
      userContactData: [],
      phoneData: [],
      creditOrderNo: null,
      letterRecordData: [],
      letterRecordLoading: false,
      isPhone: false,
      isSms: false,
      staffData: {},
      copyLoading: false
    }
  },
  mounted() {
    this.getStaffId()
    this.getOrderInfo()
    this.getUserInfo()
    this.getUserContact()
    this.getLetterRecord()
  },
  methods: {
    getStaffId() {
      getCurrentStaffId()
        .then(res => {
          if (res.success) {
            this.staffData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getOrderInfo() {
      orderInfo(this.para['orderId'])
        .then(res => {
          if (res.success) {
            this.orderInfoData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getUserInfo() {
      userInfo(this.para['orderId'])
        .then(res => {
          if (res.success) {
            this.userInfoData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getUserContact() {
      userContact(this.para.orderId)
        .then(res => {
          if (res.success) {
            this.userContactData = res.data.filter(v => {
              return v['contactGrade'] > 0
            })
            this.phoneData = res.data.sort((a, b) => {
              return a['contactName'].localeCompare(b['contactName'])
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    setContactState(item, index) {
      const data = {
        id: item['id'],
        phoneNumStatus: index
      }
      updateUserContactStatusput(data)
        .then(res => {
          if (res.success) {
            this.$message.success(this.$t('common.tip.editSuccess'))
            this.getUserContact()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getLetterRecord() {
      const params = {
        creditOrderId: this.para['creditOrderId']
      }
      riskAuditDetail(params)
        .then(res => {
          this.letterRecordLoading = false
          if (res.success) {
            this.creditOrderNo = res.data['creditOrderNO']
            this.letterRecordData = res.data['creditOrderOperateRecordVOS']
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.letterRecordLoading = false
          this.$message.error(err.message)
        })
    },
    goAnchor(data) {
      if (data === 'contactPerson') {
        const num = document.getElementById('reviewInfo').offsetTop + document.getElementById(data).offsetTop
        document.getElementById('sectionInfo').scrollTop = num
      } else {
        const num = document.getElementById(data).offsetTop
        document.getElementById('sectionInfo').scrollTop = num
      }
    },
    phoneFn(data) {
      this[data] = true
    },
    callPhone(data) {
      const account = 'EasyKlick'
      const password = 'b99846c549c57aa213fa8fe0033afdea' // 后台密码MD5
      const channelKey = 'f323ea1ffd5b4cf68a4e7d4f959955a7' // 后台channelKey
      // const voipAccount = '827404001'
      // const voipPassword = '29884818' // VOIP密码
      const voipAccount = this.staffData['recallPhone']
      const voipPassword = this.staffData['recallPhonePassword'] // VOIP密码
      const msisdn = data // 手机号，请使用0开头格式
      console.log(data)
      const extendId = this.para.orderId // 自定义的唯一扩展ID-需要绑定此通会话的id，此字段由客户提供，用于将通话记录关联进客户的通话记录中
      // 需要回调响应的Url，需要进行URL编码，格式为：http://xxxxx/xxx?extendId={extendId}&startTime={startTime}&endTime={endTime}&feeTime={feeTime}&endDirection={endDirection}&endReason={endReason}&recodingUrl={recodingUrl}
      // let postUrl = encodeURI('https://newback.kilatkre.top/urgentRecall/webcall/callback?extendId={extendId}&startTime={startTime}&endTime={endTime}&feeTime={feeTime}&endDirection={endDirection}&endReason={endReason}&recodingUrl={recodingUrl}' )
      const postUrl = encodeURI(`${process.env.VUE_APP_BASE_API}/urgentRecall/webcall/callback?extendId={extendId}&startTime={startTime}&endTime={endTime}&feeTime={feeTime}&endDirection={endDirection}&endReason={endReason}&recodingUrl={recodingUrl}`)
      console.log(window.STI)
      console.log(postUrl)
      window.STI.call('cs_msisdn', 'iframe', account, password, channelKey, voipAccount, voipPassword, msisdn, extendId, postUrl)
      this.isPhone = false
      this.call()
    },
    call() {
      $('#cs_msisdn').click()
    },
    changeDialog(data, state) {
      this[data] = state
    },
    copyClipboard() {
      const input = document.createElement('input')
      document.body.appendChild(input)
      input.setAttribute('value', this.userInfoData['phoneNumber'])
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        this.$message.success(this.$t('collectDetail.copySuccess'))
      } else {
        this.$message.error(this.$t('collectDetail.copyError'))
      }
      document.body.removeChild(input)
    },
    copyCode() {
      this.copyLoading = true
      this.$refs.repaymentCode.copyTotalLink()
    },
    setCopyLoading() {
      this.copyLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.el-main{
  padding: 0px;
}
.el-aside{
  background-color: white;
  padding: 0;
  .el-card .el-button{
    width: 100%;
  }
}
.el-aside:first-child{
  margin: 10px 0 0 10px;
}
.el-aside:last-child{
  margin: 10px;
}
.el-divider{
  margin: 15px 0;
}
.el-tabs{
  margin: 0 10px;
}
</style>
